import React, { useEffect, useRef, useState } from 'react'
import { ProTable } from '@ant-design/pro-components'
import { Button, Space, Image, Popconfirm, Modal, Badge, Input, Table, InputNumber, Spin, App } from 'antd'
import { EditTwoTone, PlusOutlined } from '@ant-design/icons'
import { useModel } from '@umijs/max'
import styles from './index.less'

const { TextArea } = Input

export default () => {
  const [isLoading, setIsLoading] = useState(false)
  const { message } = App.useApp()

  const originColumns = [
    {
      title: '商品ID',
      dataIndex: 'id'
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      render: (text, record) => (
        <Space>
          <Image width={72} src={record.goods_cover_url} />
          <a onClick={() => goProduct(3, record.id)}>{text}</a>
        </Space>
      )
    },
    {
      title: '买断价',
      dataIndex: 'buyout_price_range',
      hideInSearch: true
    },
    {
      title: '租赁信息',
      dataIndex: 'rent_meal_info',
      hideInSearch: true,
      width: 220,
      render: (text, record) => {
        const { use_scope } = record
        if (use_scope && use_scope.includes('rent')) {
          const { deposit, lease_terms, per_rent_range, periods } = text
          return (
            <>
              <div>
                押金：{deposit[0]}~{deposit[1]}
              </div>
              <div>
                租期：{periods[0]}~{periods[1]}
              </div>
              <div>
                期数：{lease_terms[0]}~{lease_terms[1]}
              </div>
              <div>
                每期租金：{per_rent_range[0]}~{per_rent_range[1]}
              </div>
            </>
          )
        } else {
          return '/'
        }
      }
    },
    {
      title: '买卖信息',
      dataIndex: 'buy_meal_info',
      hideInSearch: true,
      width: 220,
      render: (text, record) => {
        const { use_scope } = record
        if (use_scope && use_scope.includes('buy')) {
          const { first_pay_range, lease_terms, per_rent_range, periods } = text
          return (
            <>
              <div>
                首付款：{first_pay_range[0]}~{first_pay_range[1]}
              </div>
              <div>
                尾期：{lease_terms[0]}~{lease_terms[1]}
              </div>
              <div>
                期数：{periods[0]}~{periods[1]}
              </div>
              <div>
                每期尾款：{per_rent_range[0]}~{per_rent_range[1]}
              </div>
            </>
          )
        } else {
          return '/'
        }
      }
    },
    {
      title: '物流配送',
      dataIndex: 'delivery_type_names',
      hideInSearch: true,
      render: text => (
        <>
          {text.map(i => (
            <div key={i} className={styles.delivery_name}>
              {i}
            </div>
          ))}
        </>
      )
    },
    {
      title: '状态',
      dataIndex: 'after_approval_status',
      hideInSearch: true,
      width: 170,
      align: 'center',
      render: (text, record) => {
        const value = record.after_approval_status
        const enumObj = {
          1: <Badge status='processing' text={'上架中'} />,
          2: <Badge status='default' text={'已下架'} />,
          3: <Badge status='warning' text={'审核中'} />,
          4: <Badge status='warning' text={'审核中'} />,
          5: <Badge status='error' text={'审核拒绝'} />,
          6: <Badge status='error' text={'审核拒绝'} />,
          7: (
            <Badge
              status='error'
              text={
                <span>
                  强制下架
                  <a onClick={() => handleCheckReason(record)}> 查看原因</a>
                </span>
              }
            />
          )
        }
        return enumObj[value]
      }
    },
    {
      title: '总库存',
      dataIndex: 'total_store',
      hideInSearch: true,
      render: (text, record) => (
        <Space onClick={() => handleGetInventoryData(record)}>
          {text}
          <EditTwoTone />
        </Space>
      )
    },
    {
      title: '提交时间',
      dataIndex: 'create_time',
      hideInSearch: true
    },
    {
      title: '操作',
      key: 'option',
      width: 180,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        return [
          <a
            key='check'
            onClick={() => {
              goProduct(3, row.id)
            }}
          >
            详情
          </a>,
          <a
            key='edit'
            onClick={() => {
              goProduct(2, row.id)
            }}
          >
            编辑
          </a>,

          row.after_approval_status !== 7 ? (
            row.after_approval_status === 1 ? (
              <Popconfirm
                key='downShelf'
                title='是否确认将该商品下架吗?'
                onConfirm={() => handleShelf(2, [row.id])}
                okText='确认'
                cancelText='取消'
              >
                <a key='status' style={{ color: 'red' }}>
                  下架
                </a>
              </Popconfirm>
            ) : (
              <a
                key='upShelf'
                onClick={() => {
                  handleShelf(1, [row.id])
                }}
                style={{ color: '#1677ff' }}
              >
                上架
              </a>
            )
          ) : null,

          row.after_approval_status === 2 || row.after_approval_status === 7 ? (
            <Popconfirm
              key='delete'
              title='是否确认将该商品删除?'
              onConfirm={() => handleDeleteItem(row.id)}
              okText='确认'
              cancelText='取消'
            >
              <a key='delete' style={{ color: 'red' }}>
                删除
              </a>
            </Popconfirm>
          ) : null
        ]
      }
    }
  ]
  const { GetGoodsList, PostGoodsUpDownShelf, DeleteGoods, GetGoodStatusCount, GetSkuStock, UpdateSkuStock } =
    useModel('Goods')

  // 分页
  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const [goodsPageSize, setGoodsPageSize] = useState(10) //  每页数量

  // 商品列表
  const [columns, setColumns] = useState(originColumns)
  const [currentSelectedRowKeys, setCurrentSelectedRowKeys] = useState([])

  // tab 选项卡
  const [tabActiveKey, setTabActiveKey] = useState('0')
  const [tabStatusCount, setTabStatusCount] = useState({})

  const tableRef = useRef()

  // 下架原因
  const [shelfReasonModalFlag, setShelfReasonModalFlag] = useState(false)
  const [modalReason, setModalReason] = useState('')

  // 库存
  const [editInventoryModalFlag, setEditInventoryModalFlag] = useState(false)
  const [editInventoryModalList, setEditInventoryModalList] = useState([])
  const inventoryColumns = [
    {
      title: '规格',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '库存',
      dataIndex: 'store',
      key: 'store',
      render: (text, record) => (
        <InputNumber min={0} defaultValue={text} onChange={value => handleInventoryChange(value, record)} />
      )
    }
  ]
  const [inventoryCount, setInventoryCount] = useState(0)
  const [commodityId, setCommodityId] = useState(0)
  let inventorySku = {}

  // 提交库存修改
  const handleSubmitInventory = async () => {
    await UpdateSkuStock(inventorySku)
    tableRef.current.reload()
    message.success('修改成功')
    setEditInventoryModalFlag(false)
  }

  // 库存获取数据和弹窗
  const handleGetInventoryData = async row => {
    setIsLoading(true)
    const res = await GetSkuStock(row.id)
    setEditInventoryModalList(res)
    setCommodityId(row.id)

    // 计算总库存
    let count = 0
    count = res.reduce((total, item) => {
      return total + item.store
    }, 0)
    setInventoryCount(count)

    setEditInventoryModalFlag(true)
    setIsLoading(false)
  }

  // 库存数量更改
  const handleInventoryChange = (value, row) => {
    let currentIndex = editInventoryModalList.findIndex(item => item.id === row.id)
    let nweData = {
      id: commodityId,
      sku_stock: editInventoryModalList
    }
    nweData.sku_stock[currentIndex].store = value
    inventorySku = nweData
  }

  // 关闭修改库存弹窗
  const closeEditInventoryModal = () => {
    setEditInventoryModalFlag(false)
  }

  // 查看原因
  const handleCheckReason = row => {
    setModalReason(row)
    setShelfReasonModalFlag(true)
  }

  // 跳转商品页
  const goProduct = (type, id) => {
    let url = `/product?type=${type}`
    if (type !== 1 && id) {
      url += `&id=${id}`
    }
    window.open(url)
  }

  // 关闭下架原因弹窗
  const closeShelfReasonModal = () => {
    setShelfReasonModalFlag(false)
  }

  // 点击去修改
  const handleGoEdit = () => {}

  // 处理商品上下架
  const handleShelf = async (type, id) => {
    const params = {
      id,
      after_approval_status: type
    }
    await PostGoodsUpDownShelf(params)
    await handleGetGoodsList()
    tableRef.current.reload()
    message.success(type === 1 ? '上架成功' : '下架成功')
  }

  // 判断批量上下架按钮是否可用
  // const handleSelectChange = (selectedRowKeys, selectedRows) => {
  //   if (selectedRowKeys.length === 0) {
  //     setBatchShelfFlag(true);
  //   } else {
  //     setBatchShelfFlag(false);
  //     setCurrentSelectedRowKeys(selectedRowKeys);
  //   }
  // };

  // 删除
  const handleDeleteItem = async id => {
    await DeleteGoods(id)
    tableRef.current.reload()
    message.success('删除成功')
  }

  // 获取商品状态数量
  const handleGetGoodsList = async () => {
    const res = await GetGoodStatusCount()
    setTabStatusCount(res)
  }

  // 格式化 tab
  const formatTabs = () => {
    const tabsItem = [
      {
        key: 0,
        tab: '全部',
        num: '0'
      },
      {
        key: 1,
        tab: '上架中',
        num: '0'
      },
      {
        key: 2,
        tab: '已下架',
        num: '0'
      },
      {
        key: 3,
        tab: '强制下架',
        num: '0'
      }
    ]
    // 0全部，1上架，2,已下架，3强制下架
    tabStatusCount &&
      tabStatusCount.length > 0 &&
      tabStatusCount.forEach(item => {
        tabsItem[item.type].num = item.count
      })
    let arr = []
    tabsItem.forEach(item => {
      arr.push({
        key: item.key,
        tab: (
          <div>
            <span>{item.tab}</span>
            <span className={Number(item.key) === Number(tabActiveKey) ? styles.tab_badge_active : styles.tab_badge}>
              {item.num}
            </span>
          </div>
        )
      })
    })
    return arr
  }

  // 处理 tab 切换
  const handleTabActive = key => {
    setTabActiveKey(key)
    setCurrentPage(1)
    tableRef.current.reload()
  }

  return (
    <>
      {isLoading && <Spin />}

      <ProTable
        // params={{
        //   pageSize: goodsPageSize
        // }}
        scroll={{ x: 'max-content' }}
        actionRef={tableRef}
        rowSelection={{
          selectedRowKeys: currentSelectedRowKeys,
          onChange: setCurrentSelectedRowKeys
        }}
        request={async (params, sort, filter) => {
          const param = {
            page: params.current,
            page_size: params.pageSize,
            goods_name: params.goods_name,
            id: params.id,
            after_approval_status: params.after_approval_status,
            type: tabActiveKey
          }
          setGoodsPageSize(params.pageSize)
          setCurrentPage(params.current)
          const res = await GetGoodsList(param)
          await handleGetGoodsList()
          setCurrentSelectedRowKeys([])
          return {
            data: res.data,
            success: true,
            total: res.total
          }
        }}
        pagination={{
          pageSize: goodsPageSize,
          current: currentPage
        }}
        rowKey='id'
        columns={columns}
        headerTitle={
          <Button icon={<PlusOutlined />} onClick={() => goProduct(1)} key={Math.random().toString()} type='primary'>
            新增商品
          </Button>
        }
        toolBarRender={() => [
          <Button
            type='primary'
            key={Math.random().toString()}
            disabled={!currentSelectedRowKeys.length}
            onClick={() => handleShelf(1, currentSelectedRowKeys)}
          >
            上架
          </Button>,
          <Button
            danger
            key={Math.random().toString()}
            disabled={!currentSelectedRowKeys.length}
            onClick={() => handleShelf(2, currentSelectedRowKeys)}
          >
            下架
          </Button>
        ]}
        search={{
          defaultCollapsed: false,
          labelWidth: 75,
          span: 8
        }}
        toolbar={{
          multipleLine: true,
          tabs: {
            onChange: key => handleTabActive(key),
            activeKey: tabActiveKey,
            items: formatTabs()
          }
        }}
      />

      {/*下架原因弹窗*/}
      <Modal
        title={'下架原因'}
        mask
        key={Math.random().toString()}
        open={shelfReasonModalFlag}
        onCancel={closeShelfReasonModal}
        bodyStyle={{ padding: '20px' }}
        width={400}
        destroyOnClose
        footer={
          <>
            <Button onClick={closeShelfReasonModal}>关闭</Button>
            <Button type={'primary'} onClick={handleGoEdit}>
              去修改
            </Button>
          </>
        }
      >
        <div className={styles.modal_reason_content}>
          <div className={styles.modal_reason_title}>
            <span>原因类型 :</span>
            <span className={styles.modal_reason_text}> {modalReason.force_off_reason} </span>
          </div>
          <TextArea rows={4} disabled={true} value={modalReason.force_off_remark} />
        </div>
      </Modal>

      {/*修改库存弹窗*/}
      <Modal
        title={'修改库存'}
        mask
        key={Math.random().toString()}
        open={editInventoryModalFlag}
        onCancel={closeEditInventoryModal}
        bodyStyle={{ padding: '20px' }}
        width={500}
        destroyOnClose
        footer={
          <>
            <Button onClick={closeEditInventoryModal}>关闭</Button>
            <Button type={'primary'} onClick={handleSubmitInventory}>
              提交
            </Button>
          </>
        }
      >
        <div className={styles.modal_inventory_content}>
          <div className={styles.modal_inventory_title}>
            <span>总库存 :</span>
            <span>{inventoryCount}</span>
          </div>
          <Table columns={inventoryColumns} dataSource={editInventoryModalList} pagination={false} rowKey={'id'} />
        </div>
      </Modal>
    </>
  )
}
